/*
 * @Author: qjb
 *  在线用户
 * @Date: 2019-03-19 14:31:57 
 */
layui.config({}).use(['element', 'zlConfig', 'zltreemenu', 'zlContext', 'table', 'layer'], function (exports) {
	var $ = layui.$,
		zlContext = layui.zlContext,
		zltreemenu = layui.zltreemenu,
		layer = layui.layer,
		table = layui.table,
		form = layui.form,
        zlConfig = layui.zlConfig,
        statusName = zlConfig.global.result.statusName,
		msgName = zlConfig.global.result.msgName,
        dataName = zlConfig.global.result.dataName,
        OK = zlConfig.global.result.okState,
		fullheight = 'full-30',
		customCurr = 1;

	var treeObj,
        isloadsearch = false,
        isShowAll = zlContext.getCurrentUser().currentRoleId=='E555C6219EAD42A69C7DD216528B3F28'?true:false,
		treeAction = {
			loadTree: function () {
				//创建zTree组件
				treeObj = zltreemenu.render('orgTreeId', {
					dataurl: layui.cache['contentPath'] + '/manager/corefunction/queryorgddata',
					autoParam: ["RWID"],
                    tableId: 'tbUser',
                    type:'get',
                    isMove: false,
                    dataFilter: function (treeId, parentNode, responseData) {
                        if (responseData[statusName] == OK) {
                            if (isShowAll) {
                                var TopNode = {
                                    OBJNAME: "所有机构",
                                    RWID: "",
                                    SYS_PARENTID: ""
                                };
                                responseData[dataName].unshift(TopNode);
                            }
                            return responseData[dataName];
                        } else {
                            zlContext.errorMsg(responseData[msgName]);
                        }
                        return responseData;
                    }
				}, {
					onClick: function (event, treeId, treeNode) {
						customCurr = 1;
						//触发刷新的事件
						treeAction.raiseResDataEvent(treeNode);
					},
					onAsyncSuccess: function (event, treeId, treeNode, msg) {
						treeObj.selectNode(treeObj.getNodes()[0]);
						treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
					}
				})
			},
			/**发起刷新事件 */
			raiseResDataEvent: function (node) {
				var currNode = node;
				if (!node) {
					var nodes = treeObj.getSelectedNodes();
					if (nodes.length > 0)
						currNode = nodes[0];
				}
				layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, currNode);
			},
		}
	//加载树
	treeAction.loadTree();

	//渲染在线用户列表
	var userTable = table.render({
		elem: '#tbUser',
		height: fullheight,
		response: zlConfig.global.gridResponse,
		limit: 20,
		limits: [20, 50, 100, 200, 500, 1000],
		page: false,
		sortload: false,
		updId: "403577B51A1B4653AD43E2795CE72637",
		toolbar: '#toolbarOnlineUser',
        defaultToolbar: ['filter'],
		cols: [
			[ //表头
				{
					type: 'numbers',
					fixed: 'left',
					title: '#'
                },{
                    type: 'checkbox'
                },{
					field: 'ZUIHDLSJ',
					title: '登录时间',
					width: 200,
					sort: true
				}, {
					field: 'IP',
					title: '登录IP',
					width: 200
				}, {
					field: 'OBJNAME',
					title: '登录用户名',
					width: 200,
					sort: true
				}, {
					field: 'ZHANGHM',
					title: '登录账号',
                    width: 150,                    
				}
			]
		]
	});

	var gridAction = {
		currentEditObj: undefined,
		search: function () {
            isloadsearch = true;
            var layero = $(".zl-container");
            var text = $("#edtSeacherValue").val();
            var trs = layero.find('div.layui-table-main').find('tr');
            var idxs = layero.find('.layui-table-fixed').find('.layui-table-body').find('tr');
            trs.hide();
            idxs.hide();
            layero.find('.noData').remove();
            layero.find('div.layui-table-page').show();
            for (var i = 0; i < trs.length; i++) {
                var tds = $(trs[i]).find('td');
                for (var k = 0; k < tds.length; k++) {
                    var targetBox = $(tds[k]).children('div');
                    if (targetBox.children().length == 0 && targetBox.html().includes(text)) {
                        $(trs[i]).show();
                        $(idxs[i]).show();
                        break;
                    }
                }
            }
            if (layero.find('div.layui-table-main').find('tr:visible').length == 0) {
                layero.find('div.layui-table-main').append('<div class="layui-none noData">' +
                    '    <div class="empty-data" style="text-align:center;padding-top: 10%;font-size: 25px;color: #ccc;font-family: tahoma ,微软雅黑;">' +
                    '        <i class="layui-icon layui-icon-search" style="font-size: 100px;"></i>   ' +
                    '        <div style="padding-top: 10px;">无数据</div>' +
                    '    </div>' +
                    '</div>');
                layero.find('div.layui-table-page').hide();
            }
        },
        deleteRows:function(data){
            if(!data||data.length==0){
                zlContext.warnMsg('请选择需要踢出的在线用户！');
				return;
            }
            zlContext.confirm('询问', '是否要踢出选择的在线用户?', function (index) {
                zlContext.deletePost(layui.cache['contentPath'] + '/core/security/kill',
					data, function (result) {
                    layer.close(index);
					if (result[statusName] == OK) {
                        table.deleteCheckRows('tbUser');
                    }else{
                        zlContext.errorMsg("踢出用户出错："+result[msgName]); 
                    }

				});
            });
        }
	}
    
    //头工具栏事件
	table.on('toolbar(tbUser)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		switch(obj.event){
			case 'btnSeacher':
				customCurr = 1;
				gridAction.search();
				break;
			case 'delete':
				var rows = checkStatus.data;
				gridAction.deleteRows(rows);
				break;
			case 'refresh':
                treeAction.raiseResDataEvent();
				break;
		};
	});

	$('.zl-container').on('keyup','#edtSeacherValue', function (event) {
		var keyCode = event.keyCode;
		customCurr = 1;
		$('.zl-container').attr('data-search',$(this).val())
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
			$('#btnSeacher').trigger('click');
			isloadsearch = false;
		}
	});

	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (node) {
		var index = layer.msg('数据查询中，请稍候...', {
			icon: 16,
			time: false,
			shade: 0.1
		});
		var loadGridData = function (id, url, param) {
			userTable.reload({
				url: url,
				method: 'post',
				where: param,
				done: function (res, curr, count) {
					$('#edtSeacherValue').val($('.zl-container').attr('data-search'))
					layer.close(index);
					customCurr = curr
				}
			}, true);
		}
		var params = null;
		var keyvallue = $('#edtSeacherValue').val();
		if (node != null && keyvallue != '') {
			params = {
				ORGID: node.RWID,
				KEYVALUE: '%' + keyvallue + '%'
			};
			isloadsearch = true;
		} else if (node == null && keyvallue != '') {
			params = {
				KEYVALUE: '%' + keyvallue + '%'
			};
			isloadsearch = true;
		} else if (node != null && keyvallue == '') {
			params = {
				ORGID: node.RWID
			}; 
		}
		
		loadGridData('tbUser', layui.cache['contentPath'] + '/core/security/queryOnlineUser', params);
	});
	
	//iframe自适应
	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
	}).resize();

});